<template>
  <div class="app-container">
    <div class="content">
      <el-form :model="freForm" status-icon :rules="freRules" ref="freForm" label-width="100px" class="fre-form" size="mini">
        <el-form-item label="模板名称" prop="name">
          <el-input type="text" v-model="freForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="计费方式" prop="valuation_type">
          <el-radio-group v-model="freForm.valuation_type">
            <el-radio :label="3">按件数</el-radio>
            <el-radio :label="2">按重量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配送区域" prop="checkPass">
          <table class="fre-table sui-table table-bordered " style="width:900px">
            <thead>
              <tr>
                <th class="center">可配送区域</th>
                <th class="center">{{freForm.valuation_type === 3 ? '首件（个）' : '首重（个）'}}</th>
                <th class="center">运费（元）</th>
                <th class="center">{{freForm.valuation_type === 3 ? '续件（个）' : '续重（个）'}}</th>
                <th class="center">续费（元）</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in freForm.valuation_rules" :key="index">
                <td class="left-td">
                  <span v-for="area in item.regions" :key="area.id" class="area-title" :class="{'strong':area.pid==0}"> {{area.title}} </span>
                  <el-button type="text" size="small" @click="handleAreaEdit(index)">编辑</el-button>
                  <el-button type="text" size="small">删除</el-button>
                </td>
                <td class="center">
                  <el-input type="text" size="mini" v-model="item.first_amount" auto-complete="off"></el-input>
                </td>
                <td class="center">
                  <el-input type="text" size="mini" v-model="item.first_fee" auto-complete="off"></el-input>
                </td>
                <td class="center">
                  <el-input type="text" size="mini" v-model="item.additional_amount" auto-complete="off"></el-input>
                </td>
                <td class="center">
                  <el-input type="text" size="mini" v-model="item.additional_fee" auto-complete="off"></el-input>
                </td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="5">
                  <el-button type="text" size="small" @click="handleAdd">指定可配送区域和运费</el-button>
                </td>
              </tr>
            </tfoot>
          </table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('freForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--address dialog-->
    <el-dialog :visible.sync="dialogVisible" width="630px" center>
      <synctree v-if="reloadTree" :data.sync="tempList" v-model="finalData"></synctree>
      <span slot="footer" class="dialog-footer">
         <el-button @click="dialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="handleAreaSubmit">保 存</el-button>
      </span>
    </el-dialog>
    <!--address dialog-->
  </div>
</template>

<script>
  import Synctree from '@/components/Synctree'
  import originData from '@/components/Synctree/data'
  import {
    mapGetters
  } from 'vuex'
  import {
    getFreightDetail,
    addFreight,
    editFreight
  } from '@/api/freight'
  import {
    deepClone
  } from '@/utils'
  import {} from '@/api/freight'
  export default {
    components: {
      Synctree
    },
    data() {
      return {
        reloadTree: false,
        originData: originData,
        tempList: [],
        disabledKeys: [],
        templateId: this.$route.query.id,
        dialogVisible: false,
        first: true,
        finalData: [],
        disableData: [],
        editFlag: false,
        editIndex: null,
        freForm: {
          valuation_rules: [],
          name: '',
          valuation_type: 3
        },
        freData: [],
        freRules: {
          name: [{
            required: true,
            message: '请输入模版名称',
            trigger: 'blur'
          }]
        }
      }
    },

    computed: {
      ...mapGetters({
        // disabledKeys: 'dis_tree',
        abledKeys: 'able_tree'
      })
    },
    methods: {
      submitForm(formName) {
        // console.log(JSON.stringify(this.freForm))
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 编辑
            const formData = deepClone(this.freForm)
            formData.name = encodeURI(formData.name)
            formData.valuation_rules.forEach(item => {
              item.regions.forEach(key => {
                key.title = encodeURI(key.title)
              })
            })
            if (this.templateId) {
              formData.templateId = this.templateId
              editFreight(formData).then(response => {
                this.$message({
                  message: '更新成功',
                  type: 'success'
                })
              }).catch(() => {})
            } else {
              // 添加
              addFreight(formData).then(response => {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
              }).catch(() => {})
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      handleAdd() {
        this.reloadTree = true
        this.tempList = deepClone(this.originData)
        this.disabledKeys.forEach(key => {
          this.tempList.forEach(item => {
            if (key === item.id) {
              this.$set(item, 'disabled', true)
            }
          })
        })
        this.dialogVisible = true
      },
      handleAreaSubmit() {
        // 如果编辑地址
        if (this.editIndex !== null) {
          // 更新编辑数据
          this.freForm.valuation_rules[this.editIndex].regions = this.finalData
          // 编辑id重置
          this.editIndex = null
        } else {
          const temp = {
            regions: this.finalData,
            first_amount: 1,
            first_fee: '0.00',
            additional_amount: '1',
            additional_fee: '0.00'
          }
          // 添加一行数据
          if (this.finalData.length > 0) {
            this.freForm.valuation_rules.push(temp)
          }
        }
        this.abledKeys.forEach(item => {
          this.disabledKeys.push(item)
        })
        // 清空选择地址数据，为下次添加准备
        this.finalData = []
        this.dialogVisible = false
        this.reloadTree = false
      },
      findOut(target, arg) {
        return target.filter(v => !arg.includes(v))
      },
      // 编辑选择配送区域
      handleAreaEdit(index) {
        this.editIndex = index
        this.reloadTree = true
        this.finalData = this.freForm.valuation_rules[index].regions
        const abledKeys = []
        this.finalData.forEach(item => {
          abledKeys.push(item.id)
        })
        this.disabledKeys = this.findOut(this.disabledKeys, abledKeys)
        // 重新加载弹框
        this.handleAdd()
      },
      init() {
        if (this.templateId) {
          const formData = {
            templateId: this.templateId
          }
          getFreightDetail(formData).then(res => {
            this.freForm = res.data.supplierFreightDetails
          })
        }
      }
    },
    mounted() {
      this.init()
    }
  }

</script>
<style rel="stylesheet/scss" lang="scss">
  @import 'src/assets/css/sui.scss';
  .fre-form {
    .el-input,
    .el-textarea {
      width: 320px
    }
  }

  .fre-table {
    td {
      .area-title {
        color: #999999;
        &.strong {
          color: #000;
        }
      }
      .el-input {
        width: 100px;
        input {
          text-align: center;
        }
      }
    }
  }

</style>
